//
//  MemoListTableViewController.m
//  MokoAPP
//
//  Created by 현식 강 on 11. 8. 17..
//  Copyright 2011 아이온. All rights reserved.
//

#import "MemoListTableViewController.h"
#import "MokoAppDelegate.h"
#import "UIImageCategory.h"
#import "NSString+ParseQueryString.h"
#import "HTMLParser.h"
#import "GradientCell.h"
#import "MemoRootViewController.h"
#import "MemoViewerController.h"
#import "ParsingDirector.h"
#import "MemoListAllVO.h"
#import "MemoListVO.h"
@implementation MemoListTableViewController
@synthesize reloading=_reloading;
@synthesize addr;
@synthesize parent;

- (void)dealloc
{
    [viewerController release];
    [images[0] release];
    [images[1] release];
    [colorArray release];
    [memoNoDic release];
    [dataSource release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void)getMemoList {
    GET_APPDELEGATE;
    NSString* adr = [NSString stringWithFormat:@"%@?page=%d", addr, ++page];
    [delegate.httpClient requestURL:adr httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}
-(void)finishLoading:(NSData*) data {
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    vo = [director getMemoList];
    // 중복되지 않은 놈만 추가
    for( int i = 0, l = [vo.memoVOArr count]; i < l; i++ ) {
        MemoListVO* mvo = [vo.memoVOArr objectAtIndex:i];
        if( [memoNoDic objectForKey:mvo.no] == nil ) {
            [dataSource addObject:mvo];
        }
    }
    if( vo.page == page ) {
        newMessageCnt = vo.newMessageCnt;
        
    }
    
    [self.tableView reloadData];
    [self.tableView setEditing:NO animated:YES];
    
    [self dataSourceDidFinishLoadingNewData];
    [self repositionRefreshFooterView];
}

-(void)reloadFooter {
    [self getMemoList];
}
-(void)reloadHeader {
    [self firstList];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    newMessageCnt = 0;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    // 백버튼 커스터마이징
    // backBarButtonItem 이었나 암튼 이거로는 커스텀뷰가 안돼서 이렇게 지정
    page = 0;
    dataSource = [[NSMutableArray alloc] init];
    
    colorArray = [[NSArray alloc] initWithObjects:[NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,(id)[UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.0].CGColor, nil], [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,(id)(id)RGBA(199, 214, 238, 1.0).CGColor, nil], nil];
    images[0] = [[[UIImage imageNamed:@"mail.png"] ResizedLimitedWidth:25 height:0] retain];
    images[1] = [[[UIImage imageNamed:@"new.png"] ResizedLimitedWidth:25 height:0] retain];
    self.tableView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
        viewerController = [[MemoViewerController alloc] initWithNibName:@"MemoViewerController" bundle:[NSBundle mainBundle]];
    else
        viewerController = [[MemoViewerController alloc] initWithNibName:@"MemoViewerController-iPad" bundle:[NSBundle mainBundle]];
    viewerController.addr = [NSString stringWithFormat:@"%@&exec=view", addr];
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if( editingStyle == UITableViewCellEditingStyleDelete ) {
        NSString* no = ((MemoListVO*)[dataSource objectAtIndex:indexPath.row]).no;
        GET_APPDELEGATE;
        [delegate.httpClient requestURL:[NSString stringWithFormat:@"%@?exec=del&no=%@", addr, no] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(deleteDone:)];
    }
}
-(void)deleteDone:(NSData*)data {
    [parent done];
    [self firstList];
}
-(void)firstList {
    page = 0;
    [memoNoDic removeAllObjects];
    [dataSource removeAllObjects];
    [self getMemoList];
    [self.tableView setContentOffset:CGPointMake(0, 0)];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[GradientCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.opaque = NO;
        cell.textLabel.highlightedTextColor = [UIColor whiteColor];
        cell.detailTextLabel.backgroundColor = [UIColor clearColor];
        cell.detailTextLabel.opaque = NO;
        cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
    }
    if( [dataSource count] > indexPath.row ) {
        CAGradientLayer* gradientLayer = (CAGradientLayer*)cell.backgroundView.layer;
        gradientLayer.colors = [colorArray objectAtIndex:(indexPath.row & 1)];
        if( indexPath.row >= newMessageCnt ) {
            cell.imageView.image = images[0];
        } else {
            cell.imageView.image = images[1];
        }

        MemoListVO* mvo = [dataSource objectAtIndex:indexPath.row];
        cell.textLabel.text = mvo.title;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ / %@", mvo.name, mvo.date];
    }
    // Configure the cell...
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MemoListVO* mvo = [dataSource objectAtIndex:indexPath.row];
    NSString* no = mvo.no;
    NSString* name = mvo.name;
    NSString* date = mvo.date;
    
    NSString* link = mvo.link;
    [viewerController release];
    viewerController = nil;
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
        viewerController = [[MemoViewerController alloc] initWithNibName:@"MemoViewerController" bundle:nil];
    else
        viewerController = [[MemoViewerController alloc] initWithNibName:@"MemoViewerController-iPad" bundle:nil];
    viewerController.articleId = no;
    viewerController.userName= name;
    viewerController.date = date;
    viewerController.titleText = mvo.title;
    GET_APPDELEGATE;
    viewerController.addr = [NSString stringWithFormat:@"%@%@", delegate.configVO.siteHostAddress,link];
    [parent.navigationController pushViewController:viewerController animated:YES];
    
}

@end
